package com.modern.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.modern.service.QuestionManager;
import com.modern.model.Question;
import com.modern.webapp.action.BaseAction;

import java.util.List;

public class QuestionAction extends BaseAction implements Preparable {
    private QuestionManager questionManager;
    private List questions;
    private Question question;
    private Long  questionId;

    public void setQuestionManager(QuestionManager questionManager) {
        this.questionManager = questionManager;
    }

    public List getQuestions() {
        return questions;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String questionId = getRequest().getParameter("question.questionId");
            if (questionId != null && !questionId.equals("")) {
                question = questionManager.get(new Long(questionId));
            }
        }
    }

    public String list() {
        questions = questionManager.getAll();
        return SUCCESS;
    }

    public void setQuestionId(Long  questionId) {
        this. questionId =  questionId;
    }

    public Question getQuestion() {
        return question;
    }

    public void setQuestion(Question question) {
        this.question = question;
    }

    public String delete() {
        questionManager.remove(question.getQuestionId());
        saveMessage(getText("question.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (questionId != null) {
            question = questionManager.get(questionId);
        } else {
            question = new Question();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (question.getQuestionId() == null);

        questionManager.save(question);

        String key = (isNew) ? "question.added" : "question.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}